/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-07-22     86188       the first version
 */
#include "esp8266.h"
#include <at_device_esp8266.h>

#include "hal_data.h"
#include <rtdevice.h>
#include <rtthread.h>

#include <string.h>

#define LOG_TAG                        "at.sample.esp"
#include <at_log.h>
#define ESP8266_SAMPLE_DEIVCE_NAME     "esp0"

static struct at_device_esp8266 esp0 =
{
    ESP8266_SAMPLE_DEIVCE_NAME,
    ESP8266_SAMPLE_CLIENT_NAME,

    ESP8266_SAMPLE_WIFI_SSID,
    ESP8266_SAMPLE_WIFI_PASSWORD,
    ESP8266_SAMPLE_RECV_BUFF_LEN,
};

static int esp8266_device_register(void)
{
    struct at_device_esp8266 *esp8266 = &esp0;

    return at_device_register(&(esp8266->device),
                              esp8266->device_name,
                              esp8266->client_name,
                              AT_DEVICE_CLASS_ESP8266,
                              (void *) esp8266);
}
INIT_APP_EXPORT(esp8266_device_register);

const char* esp8266_init_cmd[] = {
    "AT+CWMODE=1",
    "AT+RST",
    "AT+CWJAP=\"aal\",\"10101010\"",
    "AT+ATKCLDSTA=\"46410953214843562058\",\"01010101\""
};

static at_client_t dev_esp;
int esp8266_send_data(const char* str)
{
    return at_client_obj_send(dev_esp, str, strlen(str));
}

void esp8266_init()
{
    dev_esp = at_client_get(ESP8266_SAMPLE_CLIENT_NAME);
    at_response_t resp = at_create_resp(512, 0, rt_tick_from_millisecond(5000));

    for (uint8_t i = 0; i < 4; i ++) {
        at_exec_cmd(resp, esp8266_init_cmd[i]);
        rt_thread_mdelay(1000);
    }
}

